package com.hk.jmm;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.webkit.WebView;

import com.hjq.toast.ToastUtils;
import com.hk.jmm.app.LoginActivity;
import com.hk.jmm.utils.LogUtils;
import com.skyz.base.manager.CrashManager;
import com.skyz.base.manager.EnvironmentManager;
import com.skyz.wrap.application.WrapApplication;
import com.skyz.wrap.http.UserTokenInterceptor;
import com.skyz.wrap.manager.RouteManager;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.exceptions.UndeliverableException;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
import okhttp3.OkHttpClient;

public class AppApplication extends WrapApplication {
    @Override
    public void onCreate() {

        super.onCreate();
    }

    @Override
    protected void initApplication() {
        super.initApplication();
        RouteManager.getInstance().setShowActivityListener(new RouteManager.ShowActivityListener() {
            @Override
            public void onShowActivity(Context context, String activityName, Bundle bundle) {
                switch (activityName) {
                    case "LoginActivity": {
                        LoginActivity.showActivity((Activity) context);
                        break;
                    }
                }
            }
        });
        //关于webview在Android9以后的问题处理
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            // 安卓9.0后不允许多进程使用同一个数据目录
            try {
                String processName = getProcessName(this);
                String packageName = this.getPackageName();
                if (!packageName.equals(processName)) {
                    WebView.setDataDirectorySuffix(processName);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        CrashManager.getInstance().init();
        CrashReport.initCrashReport(this, "daf260722b", false);
        //解决 io.reactivex.plugins.RxJavaPlugins.onError(RxJavaPlugins.java:367)
        setRxJavaErrorHandler();

        ToastUtils.init(this);
    }


    @Override
    protected List<EnvironmentManager.Environment> initEnvironmentList() {
        List<EnvironmentManager.Environment> environmentList = new ArrayList<>();
        environmentList.add(new EnvironmentManager.Environment("PROD",
                "https://hksvc.cel-cat.com.cn/", null,
                ""));
        environmentList.add(new EnvironmentManager.Environment("TEST",
                "http://8.134.219.9:8085/", null,
                ""));
        return environmentList;
    }

    @Override
    protected OkHttpClient initOkHttpClient() {
        return new OkHttpClient.Builder().
                connectTimeout(10L, TimeUnit.SECONDS)
                .readTimeout(10L, TimeUnit.SECONDS)
                .writeTimeout(10L, TimeUnit.SECONDS)
                .addInterceptor(new UserTokenInterceptor())
                .build();
    }

    private String getProcessName(Context context) {
        if (context == null) return null;
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
            if (processInfo.pid == android.os.Process.myPid()) {
                return processInfo.processName;
            }
        }
        return null;
    }

    private void setRxJavaErrorHandler() {
        if (RxJavaPlugins.getErrorHandler() != null || RxJavaPlugins.isLockdown()) {
            LogUtils.Log("App", "setRxJavaErrorHandler getErrorHandler()!=null||isLockdown()");
            return;
        }
        RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
            @Override
            public void accept(Throwable e) {
                if (e instanceof UndeliverableException) {
                    e = e.getCause();
                    LogUtils.Log("App", "setRxJavaErrorHandler UndeliverableException=" + e);
                    return;
                } else if ((e instanceof IOException)) {
                    // fine, irrelevant network problem or API that throws on cancellation
                    return;
                } else if (e instanceof InterruptedException) {
                    // fine, some blocking code was interrupted by a dispose call
                    return;
                } else if ((e instanceof NullPointerException) || (e instanceof IllegalArgumentException)) {
                    // that's likely a bug in the application
                    Thread.UncaughtExceptionHandler uncaughtExceptionHandler =
                            Thread.currentThread().getUncaughtExceptionHandler();
                    if (uncaughtExceptionHandler != null) {
                        uncaughtExceptionHandler.uncaughtException(Thread.currentThread(), e);
                    }
                    return;
                } else if (e instanceof IllegalStateException) {
                    // that's a bug in RxJava or in a custom operator
                    Thread.UncaughtExceptionHandler uncaughtExceptionHandler =
                            Thread.currentThread().getUncaughtExceptionHandler();
                    if (uncaughtExceptionHandler != null) {
                        uncaughtExceptionHandler.uncaughtException(Thread.currentThread(), e);
                    }
                    return;
                }
                LogUtils.Log("App", "setRxJavaErrorHandler unknown exception=" + e);
            }
        });
    }
}
